﻿using CefSharp;
using CefSharp.WinForms;
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;

namespace BaseFrame.Tool.CefSharp
{
    public static class CefProxyOptions
    {
        public static ChromiumWebBrowser Create(string url)
        {
            return new ChromiumWebBrowser(url);
        }

        /// <summary>
        /// 跳转导航
        /// </summary>
        /// <param name="webview"></param>
        /// <param name="url"></param>
        public static void NavOrCreateWebBrowser(ref ChromiumWebBrowser webview, string url, string cookieName = "userInfoCookie")
        {
            if (webview != null && !webview.IsDisposed)
            {
                webview.Load(url);
            }
            else
            {
                webview = CreateSingleCookie(url, cookieName);
            }
        }
        /// <summary>
        /// 自动登录保存会话
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="userName">用户名称（自定义）</param>
        /// <returns></returns>
        public static ChromiumWebBrowser CreateSingleCookie(string url, string userName)
        {
            RequestContextSettings requestContextSettings = new RequestContextSettings()
            {
                PersistSessionCookies = true,
                PersistUserPreferences = true,
                CachePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "CefSharp\\Cache_" + userName)
            };
            #region 保存登录会话（自动登录，如果不需要直接全部注释掉就好）
            CefSettings settings = new CefSettings();
            string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "CefSharp\\Cache_" + userName);
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            settings.CachePath = path;
            Cef.Initialize(settings);
            #endregion
            var browser = new ChromiumWebBrowser(url)
            {
                RequestContext = new RequestContext(requestContextSettings)
            };
            return browser;
        }
        /// <summary>
        /// 自动登录不保存会话
        /// </summary>
        /// <param name="url"></param>
        /// <param name="userName"></param>
        /// <returns></returns>
        public static ChromiumWebBrowser CreateSingleCookieNotSaveLoginInfo(string url, string userName)
        {
            RequestContextSettings requestContextSettings = new RequestContextSettings
            {
                PersistSessionCookies = false,
                PersistUserPreferences = false,
                CachePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "CefSharp\\Cache_" + userName)
            };
            var browser = new ChromiumWebBrowser(url)
            {
                RequestContext = new RequestContext(requestContextSettings)
            };
            return browser;
        }
        /// <summary>
        /// 实行JavaScript脚本
        /// </summary>
        /// <param name="script">执行脚本</param>
        /// <param name="Browser"></param>
        /// <returns></returns>
        public static async Task<bool> EvaluateJavascript(string script, ChromiumWebBrowser Browser)
        {
            JavascriptResponse javascriptResponse = await Browser.GetMainFrame().EvaluateScriptAsync(script);
            if (!javascriptResponse.Success)
                return false;
            else
                return true;
        }


        #region 快手相关

        /// <summary>
        /// 模拟一个登录脚本执行方法
        /// </summary>
        /// <param name="webBrowser"></param>
        /// <param name="userName"></param>
        /// <param name="userPwd"></param>
        public static void SetNameAndPwd(ChromiumWebBrowser webBrowser, string userName, string userPwd)
        {
            _ = EvaluateJavascript($"var account = document.getElementsByClassName(\"ant-input\")[0]", webBrowser); //账号
            _ = EvaluateJavascript($"account.value = \"{userName}\";", webBrowser);
            _ = EvaluateJavascript("var eventAccount = new Event('input', { bubbles: true });", webBrowser);
            _ = EvaluateJavascript("var trackerAccount = account._valueTracker;", webBrowser);
            _ = EvaluateJavascript("if (trackerAccount) {trackerAccount.setValue('');}", webBrowser);
            _ = EvaluateJavascript("account.dispatchEvent(eventAccount);", webBrowser);

            _ = EvaluateJavascript($"var pwdInput = document.getElementsByClassName(\"ant-input\")[1]", webBrowser); //密码
            _ = EvaluateJavascript($"pwdInput.value = \"{userPwd}\";", webBrowser);
            _ = EvaluateJavascript("var eventPwd = new Event('input', { bubbles: true });", webBrowser);
            _ = EvaluateJavascript("var trackerPwd = pwdInput._valueTracker;", webBrowser);
            _ = EvaluateJavascript("if (trackerPwd) {trackerPwd.setValue('');}", webBrowser);
            _ = EvaluateJavascript("pwdInput.dispatchEvent(eventPwd);", webBrowser);

            _ = EvaluateJavascript("document.getElementsByClassName(\"ant-btn\")[0].click()", webBrowser); //登录
        }
        /// <summary>
        /// 切换到账号密码登陆脚本
        /// </summary>
        /// <param name="webBrowser"></param>
        public static void SelectStaffLoginJs(ChromiumWebBrowser webBrowser)
        {
            _ = EvaluateJavascript($"document.getElementsByClassName(\"choose-account-type\")[0].children[2].click()", webBrowser); //输入验证码
        }
        /// <summary>
        /// 模拟发送消息
        /// </summary>
        /// <param name="sendText"></param>
        /// <param name="webview"></param>
        /// <param name="sleepTimes"></param>
        /// <returns></returns>
        public static bool SendMessage(string sendText, ChromiumWebBrowser webview, int[] sleepTimes)
        {
            string sendTextTest = sendText;
            _ = EvaluateJavascript("var input = document.getElementsByClassName(\"editor\")[0]", webview);
            _ = EvaluateJavascript($"input.innerHTML = \"{sendTextTest}\";", webview);
            _ = EvaluateJavascript("var event = new Event('input', { bubbles: true });", webview);
            _ = EvaluateJavascript("var tracker = input._valueTracker;", webview);
            _ = EvaluateJavascript("if (tracker) {tracker.setValue('');}", webview);
            _ = EvaluateJavascript("input.dispatchEvent(event);", webview);
            Thread.Sleep(sleepTimes[0]);
            KeyEvent k = new KeyEvent
            {
                WindowsKeyCode = 0x0D, // Enter
                FocusOnEditableField = true,
                IsSystemKey = false,
                Type = KeyEventType.KeyDown
            };
            webview.GetBrowser().GetHost().SendKeyEvent(k);
            Thread.Sleep(sleepTimes[1]);
            k = new KeyEvent
            {
                WindowsKeyCode = 0x0D, // Enter
                FocusOnEditableField = true,
                IsSystemKey = false,
                Type = KeyEventType.KeyUp
            };
            webview.GetBrowser().GetHost().SendKeyEvent(k);
            return true;
        }

        /// <summary>
        /// 模拟选择时间，订单检索查询
        /// </summary>
        /// <param name="webview"></param>
        /// <param name="beginTimeValue">开始时间</param>
        /// <param name="endTimeValue">结束时间</param>
        /// <param name="sleepTimes"></param>
        public static void ToSetBeginAndEndTimeJs(ChromiumWebBrowser webview, string beginTimeValue, string endTimeValue, int[] sleepTimes)
        {
            Thread.Sleep(sleepTimes[0]);
            _ = EvaluateJavascript("document.getElementsByClassName(\"order-time ant-calendar-picker\")[0].children[0].click()", webview);//打开时间选择框
            Thread.Sleep(sleepTimes[0]);
            _ = EvaluateJavascript("var timeBegin = null", webview);
            _ = EvaluateJavascript("document.getElementsByClassName(\"ant-calendar-input \")[0].click()", webview);
            _ = EvaluateJavascript("timeBegin = document.getElementsByClassName(\"ant-calendar-input \")[0]", webview);
            _ = EvaluateJavascript($"timeBegin.value = \"{beginTimeValue}\";", webview);//设置开始时间
            _ = EvaluateJavascript("var eventBegin = new Event('input', { bubbles: true });", webview);
            _ = EvaluateJavascript("var trackerBegin = timeBegin._valueTracker;", webview);
            _ = EvaluateJavascript("if (trackerBegin) {trackerBegin.setValue('');}", webview);
            _ = EvaluateJavascript("timeBegin.dispatchEvent(eventBegin);", webview);
            Thread.Sleep(sleepTimes[1]);
            _ = EvaluateJavascript("var timeEnd = null", webview);
            _ = EvaluateJavascript("document.getElementsByClassName(\"ant-calendar-input \")[1].click()", webview);
            _ = EvaluateJavascript("timeEnd = document.getElementsByClassName(\"ant-calendar-input \")[1]", webview);
            _ = EvaluateJavascript($"timeEnd.value = \"{endTimeValue}\";", webview);//设置结束时间
            _ = EvaluateJavascript("var eventEnd = new Event('input', { bubbles: true });", webview);
            _ = EvaluateJavascript("var trackerEnd = timeEnd._valueTracker;", webview);
            _ = EvaluateJavascript("if (trackerEnd) {trackerEnd.setValue('');}", webview);
            _ = EvaluateJavascript("timeEnd.dispatchEvent(eventEnd);", webview);
            _ = EvaluateJavascript("document.getElementsByClassName(\"ant-calendar-ok-btn\")[0].click()", webview);//确认选择时间
            Thread.Sleep(sleepTimes[2]);
            _ = EvaluateJavascript("document.getElementsByClassName(\"ant-btn ant-btn-primary\")[0].click()", webview);//筛选操作
        }
        #endregion


    }
}
